package adventure.placeable.trigger.results;

import adventure.placeable.trigger.Trigger;
import adventure.placeable.trigger.TriggerImp;
import player.Player;
import adventure.room.RoomManager;
import adventure.room.RoomManagerEdit;
import colour.ColourUtil;
import server.util.Broadcaster;

/**
 *
 * @author Michael Hanns
 *
 */
public class ResultSpawnTrigger extends TriggerResult implements Cloneable {

    private Trigger t;

    public ResultSpawnTrigger(String result, Trigger t) {
        super(result);
        this.t = t;
    }

    public ResultSpawnTrigger(String result, int uses, Trigger t) {
        super(result, uses);
        this.t = t;
    }

    public ResultSpawnTrigger() {
        super();
        t = new TriggerImp();
    }

    public void setTrigger(Trigger trigger) {
        t = trigger;
    }

    public int getTriggerID() {
        return t.getID();
    }

    @Override
    public String getDescription() {
        if (super.limitedUses()) {
            String desc = super.resultText + ", uses: " + super.usesRemaining()
                    + " / SPAWNTRIGGER " + t.getName();
            return desc;
        } else {
            String desc = super.resultText + " / SPAWNTRIGGER " + t.getName();
            return desc;
        }
    }

    @Override
    public String resultImplementation(RoomManager r, Player p, String i, boolean previousFailed, Broadcaster out) {
        if (allConditionsMet(r, p, i, previousFailed)) {
            ((RoomManagerEdit)r).addTriggerToRoom(t.cloneThis(), p.x(), p.y(), p.z());
            useOnce();
            
            String output = replaceKeywords(p);
            
            out.broadcastLocalToPlayer(p, replaceYou(output, p, true));
            
            return replaceYou(output, p, false);    
        } else {
            return "";
        }
    }

    @Override
    public String getType() {
        return "SPAWNTRIGGER";
    }

    @Override
    public String replaceKeywords(Player p) {
        return resultText
                .replace("[PLAYER]", ColourUtil.colourise(p.getName(), ColourUtil.player)
                .replace("[TRIGGER]", ColourUtil.colourise(t.getName(), ColourUtil.trigger))
                .replace("[USES]", ColourUtil.colourise(super.usesRemaining() + "", ColourUtil.value)));
    }

}